package com.system.weirdor.facade.provider.impl;

import com.system.weirdor.common.constant.SystemConstant;
import com.system.weirdor.facade.provider.ResourceFacedeApi;
import com.system.weirdor.facade.shiro.vo.R;
import com.system.weirdor.module.entity.ResourceEntity;
import com.system.weirdor.module.mapper.ResourceMapper;
import com.system.weirdor.module.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Service
public class ResourceApilmpl implements ResourceFacedeApi {

    @Autowired
    private ResourceMapper resourceMapper;

@Autowired
private UserMapper userMapper;

    @Override
    public List<ResourceEntity> listMenu(Map<String, Object> params) {

        List<ResourceEntity> menuLIst=resourceMapper.listMenu();

        return menuLIst;
    }

    @Override
    public List<ResourceEntity> listParentId(Long parentId, List<Long> menuIdList) {
        List<ResourceEntity> menuList = resourceMapper.listParentId(parentId);
        if(menuIdList == null){
            return menuList;
        }

        List<ResourceEntity> userMenuList = new ArrayList<>();
        for(ResourceEntity menu : menuList){
            if(menuIdList.contains(menu.getMenuId())){
                userMenuList.add(menu);
            }
        }
        return userMenuList;
    }

    public R listUserMenu(Long userId) {
        return R.ok().put("data", listUserMenus(userId));
    }

    public List<ResourceEntity> listUserMenus(Long userId) {
        List<Long> menuIdList = userMapper.listAllMenuId(userId);
        return getAllMenuList(menuIdList);
    }
    /**
     * 获取所有菜单列表
     */
    private List<ResourceEntity> getAllMenuList(List<Long> menuIdList){
        //查询根菜单列表
        List<ResourceEntity> menuList = listParentId(0L, menuIdList);
        //递归获取子菜单
        getMenuTreeList(menuList, menuIdList);

        return menuList;
    }

    /**
     * 递归
     */
    private List<ResourceEntity> getMenuTreeList(List<ResourceEntity> menuList, List<Long> menuIdList){
        List<ResourceEntity> subMenuList = new ArrayList<ResourceEntity>();

        for(ResourceEntity entity : menuList){
            System.out.println(entity.getType());
            if(entity.getType() == SystemConstant.MenuType.CATALOG.getValue()){//目录
           //     entity.setList(getMenuTreeList(listParentId(entity.getMenuId(), menuIdList), menuIdList));
                entity.setSubset(getMenuTreeList(listParentId(entity.getMenuId(), menuIdList), menuIdList));
            }
            subMenuList.add(entity);
        }
        return subMenuList;
    }

}
